package Project4;

import java.util.*;

class WhileStatement extends Statement{
	private ArrayList<Statement> trueStatements = new ArrayList<Statement>();
	private int labelCounter = 0;
	public boolean optimizedFalse = false;
	public boolean optimizedTrue = false;
	public BooleanStatement booleanStatement;

	public WhileStatement(int labelCounter){
		this.labelCounter = labelCounter;
	}

	public void addBody(ArrayList<Statement> t){
		trueStatements = t;
	} 

	public void addBoolean(BooleanStatement bs){
		booleanStatement = bs;
	}

	public String toString(){
		String r = "";
		String branchCondition = buildBranchCondition();
		
		if(optimizedFalse){
			return r += " #Loop optimized away -- while(FALSE) \n";
		}

		r += "#While Loop \n";
		r += "LOOP_START_" + labelCounter + ":\n";
		r += optimizedTrue ? "#Loop optimized to true -- while(TRUE) \n" : branchCondition + " LOOP_END_" + labelCounter + "\n";
		for(Statement s: trueStatements){
			r += s + "\n";
		}
		r += "j LOOP_START_" + labelCounter + "\n";
		r += "LOOP_END_" + labelCounter + ":\n";
		r += "#end while";
		return r;
	}

	private String buildBranchCondition(){
		if(booleanStatement == null){
			return "";
		}
		String b = "";
		b += "li $s6, " + booleanStatement.getFirstExpression().getValue() + "\n";
		b += "li $s7, " + booleanStatement.getSecondExpression().getValue() + "\n";
		b += booleanStatement.getConditional() + "$s6, $s7 ";
		return b;
	}
}
